package com.iamk.tool;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import net.miginfocom.swing.MigLayout;
import net.semanticmetadata.lire.imageanalysis.cedd.MaskResults;

import com.iamk.feature.FColor;
import com.iamk.util.Convert;
import com.iamk.util.GetData;
import com.iamk.util.ListFilesUtil;

public class ManualAnnotation extends JPanel implements ActionListener{

	private static final long serialVersionUID = -6379686852384264519L;

	final String[] LABEL = { 
							"building",
							"grass",
							"tree",
							"sky",
							"water",
							"road",
							"body"};

	JButton btnOpenFolder;
	JButton btnClear;
	JButton btnSet;
	JButton btnWriteLevel1Data;
	JButton btnSaveMask;

	JRadioButton rdbUseTrainingSet;
	JRadioButton rdbUseCrossValidation;

	JList<String> lsLabel;
	JScrollPane scrollLabel;
	
	JList<String> lsFileName;
	JScrollPane scrollFileName;
	
	JTextArea txtResult;
	JScrollPane scrollResult;

	JLabel lblPath;
	JLabel lblClassifer;
	JLabel lblFold;
	
	JLabel picImageOriginLabel;
	JLabel picImageSegmentLabel;

	JTextField tfPath;
	JTextField tfFold;

	JPanel mPanelImageOriginal;
	JPanel mPanelImageSegmentation;
	JPanel mPanelFileName;
	JPanel mPanelChooserLabel;
	JPanel mPanelLabelResult;
	JPanel mPanelManualLabel;
	JPanel mPanelAutoLabel;

	JScrollPane dataPane;
	JScrollPane outputPane;
	
	JList<String> lsManualLabel;
	JScrollPane manualLabelPane;
	
	JList<String> lsAutoLabel;
	JScrollPane autoLabelPane;

	JTextArea txtData;
	JTextArea txtOutput;

	JFileChooser dlgChooseFolder;

	String path;
	
	Image imgOriginal;
	Image imgSegmentation;
	FColor fImage;
	int regionSelected;
	
	ListFilesUtil lfu = new ListFilesUtil();
	public ManualAnnotation() {
		// TODO Auto-generated constructor stub
		super(null);
		setPropertiesComponent();
	}

	void setPropertiesComponent() {
		// Init view
		lblPath = new JLabel("Path: ");
		lblPath.setSize(new Dimension(50, 30));
		lblPath.setLocation(30, 20);

		btnOpenFolder = new JButton("Open");
		btnOpenFolder.setSize(new Dimension(70, 30));
		btnOpenFolder.setLocation(550, 20);
		btnOpenFolder.setActionCommand("Open");
		btnOpenFolder.setVisible(true);
		btnOpenFolder.addActionListener(this);
		
		btnClear = new JButton("Clear");
		btnClear.setSize(new Dimension(70, 30));
		btnClear.setLocation(650, 20);
		btnClear.setActionCommand("Clear");
		btnClear.setVisible(true);
		btnClear.addActionListener(this);

		btnSet = new JButton("Set label");
		btnSet.setSize(new Dimension(120, 30));
		btnSet.setLocation(790, 80);
		btnSet.setActionCommand("Set");
		btnSet.setVisible(true);
		btnSet.addActionListener(this);
		
		btnSaveMask = new JButton("Save mask");
		btnSaveMask.setSize(new Dimension(120, 30));
		btnSaveMask.setLocation(930, 80);
		btnSaveMask.setActionCommand("Save");
		btnSaveMask.setVisible(true);
		btnSaveMask.addActionListener(this);

		tfPath = new JTextField();
		tfPath.setSize(430, 30);
		tfPath.setMargin(new Insets(3, 3, 3, 3));
		tfPath.setLocation(80, 20);
		// Panel File Input
		mPanelFileName = new JPanel(new BorderLayout());
		mPanelFileName.setBorder(BorderFactory.createTitledBorder("File name"));
		mPanelFileName.setSize(new Dimension(240, 150));
		mPanelFileName.setLocation(30, 60);
		
		lsFileName = new JList<String>();
		lsFileName.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		lsFileName.addListSelectionListener(lsFileListener);
		scrollFileName = new JScrollPane(lsFileName,
				ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
				ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		mPanelFileName.add(scrollFileName);
		// Panel Choose Label
		mPanelChooserLabel = new JPanel(new BorderLayout());
		mPanelChooserLabel.setBorder(BorderFactory.createTitledBorder("Label"));
		mPanelChooserLabel.setSize(new Dimension(240, 150));
		mPanelChooserLabel.setLocation(280, 60);
		
		lsLabel = new JList<String>(LABEL);
		lsLabel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		scrollLabel = new JScrollPane(lsLabel,
				ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
				ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		mPanelChooserLabel.add(scrollLabel);

		// Panel Label Result
		mPanelLabelResult = new JPanel(new BorderLayout());
		mPanelLabelResult.setBorder(BorderFactory.createTitledBorder("Label Result"));
		mPanelLabelResult.setSize(new Dimension(240, 150));
		mPanelLabelResult.setLocation(540, 60);

		txtResult = new JTextArea();
		scrollResult = new JScrollPane(txtResult,
				ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
				ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		mPanelLabelResult.add(scrollResult);
		// Panel Image Original
		mPanelImageOriginal = new JPanel(new MigLayout());
		mPanelImageOriginal.setBorder(BorderFactory.createTitledBorder("Image Original"));
		mPanelImageOriginal.setSize(new Dimension(500, 400));
		mPanelImageOriginal.setLocation(30, 230);
		
		// Panel Image Segmentation
		mPanelImageSegmentation = new JPanel(new MigLayout());
		mPanelImageSegmentation.setBorder(BorderFactory.createTitledBorder("Image Segmentation"));
		mPanelImageSegmentation.setSize(new Dimension(500, 400));
		mPanelImageSegmentation.setLocation(530, 230);
		
		// Panel Manual Label
		mPanelManualLabel = new JPanel(new BorderLayout());
		mPanelManualLabel.setBorder(BorderFactory.createTitledBorder("Manual Label"));
		mPanelManualLabel.setSize(new Dimension(400, 300));
		mPanelManualLabel.setLocation(30, 650);
		
		lsManualLabel = new JList<String>();
		lsManualLabel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		manualLabelPane = new JScrollPane(lsManualLabel,
				ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
				ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		mPanelManualLabel.add(manualLabelPane);

		// Panel Auto Label
		mPanelAutoLabel = new JPanel(new BorderLayout());
		mPanelAutoLabel.setBorder(BorderFactory.createTitledBorder("Auto Label"));
		mPanelAutoLabel.setSize(new Dimension(400, 300));
		mPanelAutoLabel.setLocation(450, 650);
		
		lsAutoLabel = new JList<String>();
		lsAutoLabel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		autoLabelPane = new JScrollPane(lsAutoLabel,
				ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
				ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		mPanelAutoLabel.add(autoLabelPane);

		
		this.add(lblPath);
		this.add(tfPath);
		this.add(btnOpenFolder);
		this.add(btnClear);
		this.add(mPanelChooserLabel);
		this.add(btnSet);
		this.add(btnSaveMask);
		this.add(mPanelImageOriginal);
		this.add(mPanelImageSegmentation);
		this.add(mPanelFileName);
		this.add(mPanelLabelResult);
//		this.add(mPanelManualLabel);
//		this.add(mPanelAutoLabel);

	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		switch (e.getActionCommand()) {
		case "Open":
			dlgChooseFolder = new JFileChooser();
			dlgChooseFolder.setCurrentDirectory(new File("C:/Users/sev_user/Desktop/New_Dataset/"));
			dlgChooseFolder.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
			dlgChooseFolder.setAcceptAllFileFilterUsed(false);
			int returnVal = dlgChooseFolder.showOpenDialog(ManualAnnotation.this);
		    if(returnVal == JFileChooser.APPROVE_OPTION) {
				path = dlgChooseFolder.getSelectedFile().toString();
				tfPath.setText(path);
				lfu.listAllFiles(path);
				lsFileName.setListData(lfu.convertToArrayString(lfu.arrFileName));
				lsFileName.setSelectedIndex(0);
				lsFileName.revalidate();
				
				loadImage(lfu.arrAllFile.get(lsFileName.getSelectedIndex()));
				String filename = lfu.arrFileName.get(lsFileName.getSelectedIndex());
				filename = filename.replace(".jpg", "");
				filename = filename.replace(".bmp", "");
				loadSegment(filename);
		    }
			break;
		case "Set":
			// Save label of region
//			File file = new File(System.getProperty("user.dir") + "\\label\\labels-boat.txt");
//			try {
//				BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
//				String filename = lfu.arrFileName.get(lsFileName.getSelectedIndex());
////				filename = filename.replace(".jpg", "");
//				bw.write(filename + "," + regionSelected + "," + Convert.switchLabel(lsLabel.getSelectedValue()) +"\n");
//				bw.close();
//				
//				txtResult.setText("");
//				FileReader reader = new FileReader(file);
//                BufferedReader br = new BufferedReader(reader);
//                txtResult.read( br, null );
//			} catch (IOException excep) {
//				excep.printStackTrace();
//			}
			if(!fImage.listLabel.contains(Convert.switchLabel(lsLabel.getSelectedValue()))){
				fImage.listLabel.add(Convert.switchLabel(lsLabel.getSelectedValue()));
			}
			
			for(int i = 0; i < fImage.mask.length; i++){
				for(int j = 0; j < fImage.mask[0].length; j++){
					if(fImage.mask[i][j] == regionSelected){
						fImage.mask[i][j] = Integer.valueOf(Convert.switchLabel(lsLabel.getSelectedValue()));
					}
				}
			}
			break;
		case "Save":
			String filename = lfu.arrFileName.get(lsFileName.getSelectedIndex());
			filename = filename.replace(".bmp", "");
			filename = filename.replace(".jpg", "");
			// Replace non region by 1
			for(int i = 0; i < fImage.mask.length; i++){
				for(int j = 0; j < fImage.mask[0].length; j++){
					if(fImage.mask[i][j] >=0 ){
						fImage.mask[i][j] = 1;
					}
				}
			}
			// Reverse sign of label
			for (int i = 0; i < fImage.mask.length; i++) {
				for (int j = 0; j < fImage.mask[0].length; j++) {
					fImage.mask[i][j] = -fImage.mask[i][j];
				}
			}
			fImage.saveMask(System.getProperty("user.dir")+"\\mask\\" + filename + ".txt", fImage.mask);
			break;
		default:
			break;
		}
	}
	
	MouseListener segmentListener = new MouseListener() {
		@Override
		public void mouseReleased(MouseEvent e) {
		}
		
		@Override
		public void mousePressed(MouseEvent e) {
		}
		
		@Override
		public void mouseExited(MouseEvent e) {
		}
		
		@Override
		public void mouseEntered(MouseEvent e) {
		}
		
		@Override
		public void mouseClicked(MouseEvent e) {
			System.out.println(e.getX() +"/"+ e.getY());
			regionSelected = fImage.mask[e.getX()][e.getY()];
			BufferedImage fgImage = GetData.getRegion(GetData.copyImage(GetData.toBufferedImage(imgSegmentation)), fImage.mask, regionSelected);
			mPanelImageSegmentation.removeAll();
			picImageSegmentLabel = new JLabel(new ImageIcon(fgImage));
			picImageSegmentLabel.addMouseListener(segmentListener);
			mPanelImageSegmentation.add(picImageSegmentLabel);
			mPanelImageSegmentation.revalidate();
		}
	};
	
	ListSelectionListener lsFileListener = new ListSelectionListener() {
		@Override
		public void valueChanged(ListSelectionEvent e) {
			if(!e.getValueIsAdjusting()){
				loadImage(lfu.arrAllFile.get(lsFileName.getSelectedIndex()));
				String filename = lfu.arrFileName.get(lsFileName.getSelectedIndex());
				filename = filename.replace(".jpg", "");
				filename = filename.replace(".bmp", "");
				loadSegment(filename);
			}
		}
	};
	
	private void loadImage(String path){
		try {
			imgOriginal = ImageIO.read(new File(path));
			picImageOriginLabel = new JLabel(new ImageIcon((BufferedImage)imgOriginal));
			mPanelImageOriginal.removeAll();
			mPanelImageOriginal.add(picImageOriginLabel);
			mPanelImageOriginal.revalidate();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void loadSegment(String filename){
		fImage = new FColor((BufferedImage)imgOriginal, filename, "");
		imgSegmentation = fImage.imgSeg;
		picImageSegmentLabel = new JLabel(new ImageIcon(imgSegmentation));
		picImageSegmentLabel.addMouseListener(segmentListener);
		mPanelImageSegmentation.removeAll();
		mPanelImageSegmentation.add(picImageSegmentLabel);
		mPanelImageSegmentation.revalidate();
	}
}
